//
//  DYWebViewController.swift
//  QuRongXiang
//
//  Created by qurongxiang on 2018/7/4.
//  Copyright © 2018年 zhaowang. All rights reserved.
//

import UIKit
import WebKit

class DYWebViewController: BaseViewController {
    
    private lazy var webView: WKWebView = {
        let config = WKWebViewConfiguration()
        // 设置偏好设置
        config.preferences = WKPreferences()
        // 默认为0
        // config.preferences.minimumFontSize = 10
        // 默认认为YES
        config.preferences.javaScriptEnabled = true
        // 在iOS上默认为NO，表示不能自动通过窗口打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = false
        // web内容处理池，由于没有属性可以设置，也没有方法可以调用，不用手动创建
        config.processPool = WKProcessPool()
        // 通过JS与webview内容交互
        config.userContentController = WKUserContentController()
        // 注入JS对象名称AppModel，当JS通过AppModel来调用时，
        // 我们可以在WKScriptMessageHandler代理中接收到
        config.userContentController.add(self, name: "AppModel")
        let web = WKWebView(frame: view.bounds, configuration: config)
        web.navigationDelegate = self
        web.uiDelegate = self
        return web
    }()
    
    
    fileprivate var progressView = UIProgressView()
    
    var  myUrl:String = ""
    var  myTitle:String = ""
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupUI()
        self.title = self.myTitle
        let url = URL(string: self.myUrl)
        var request: URLRequest? = nil
        if let anUrl = url {
            request = URLRequest(url: anUrl)
        }
        if let aRequest = request {
            webView.load(aRequest)
        }
        
    }
    
}

extension DYWebViewController {
    func setupUI() {
        view.addSubview(webView)
        webView.snp.makeConstraints { (make) in
            make.top.equalTo(view).offset(LayoutCommon.navHeight)
            make.left.right.equalToSuperview()
            if #available(iOS 11.0, *) {
                make.bottom.equalTo(view.safeAreaLayoutGuide.snp.bottom)
            } else {
                make.bottom.equalTo(view.snp.bottom)
            }
        }
        webView.addObserver(self, forKeyPath: "estimatedProgress", options: .new, context: nil)
        
        webView.addSubview(progressView)
        progressView.frame = CGRect(x: 0, y: 0, width: LayoutCommon.width, height: 1)
        progressView.progressTintColor = UIColor.green
        progressView.trackTintColor = UIColor.blue
    }
}

extension DYWebViewController: WKUIDelegate, WKNavigationDelegate,WKScriptMessageHandler {
    ///监听进度
    override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
        if (keyPath == "estimatedProgress") {
            progressView.progress = Float(self.webView.estimatedProgress)
        }
    }
    
    
    
    
    ///完成
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
         progressView.isHidden = true
    }
    /// 加载失败
    func webView(_ webView: WKWebView, didFail navigation: WKNavigation!, withError error: Error) {
        //self.webLoadFaild()
    }
    
    func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
        //        debugPrint(message.body,message.name)
        //        if let body =  message.body as? [String: String]  {
        //            if let isAlert = body["isAlert"] , isAlert == "true" {
        //                self.showAlert(message: body["body"] ?? "")
        //            }else{
        //                self.navigationController?.popViewController(animated: true)
        //            }
        //        }
    }
}
